export default class SSEFetcher {
  private _url: string;
  private _callBack: (data: string) => void;
  private controller: AbortController | null = null;
  private isRunning: boolean = true;
  private retryCount: number = 0;
  private maxRetries: number = 3;

  constructor(url: string, callBack: (data: string) => void) {
    this._url = url;
    this._callBack = callBack;
    console.log('SSEFetcher 初始化，URL:', url);
    this.startConnection();
  }

  // 使用 fetch 实现 SSE 连接，支持自定义 headers
  private async startConnection() {
    this.stop(); // 确保关闭之前的连接
    
    console.log(`SSE 开始连接 (第${this.retryCount + 1}次尝试):`, this._url);
    
    try {
      this.controller = new AbortController();
      
      // 获取认证 token
      const token = localStorage.getItem('token') || '';
      
      const response = await fetch(this._url, {
        method: 'GET',
        headers: {
          'Accept': 'text/event-stream',
          'Cache-Control': 'no-cache',
          'Authorization': `Bearer ${token}`,
        },
        signal: this.controller.signal,
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      console.log('SSE 连接成功');
      this.retryCount = 0;

      const reader = response.body?.getReader();
      const decoder = new TextDecoder();

      if (reader) {
        while (this.isRunning) {
          const { done, value } = await reader.read();
          if (done) break;

          const chunk = decoder.decode(value, { stream: true });
          const lines = chunk.split('\n');

          for (const line of lines) {
            if (line.startsWith('data: ')) {
              const data = line.slice(6);
              if (data.trim()) {
                console.log('SSE 收到消息:', data);
                this._callBack(data);
              }
            }
          }
        }
      }
    } catch (error) {
      console.error('SSE 连接错误:', error);
      
      if (this.retryCount < this.maxRetries && this.isRunning) {
        this.retryCount++;
        console.log(`SSE 将在3秒后重试 (${this.retryCount}/${this.maxRetries})`);
        setTimeout(() => {
          if (this.isRunning) this.startConnection();
        }, 3000);
      } else {
        console.error('SSE 连接失败，已达到最大重试次数');
        this.isRunning = false;
      }
    }
  }

  // 停止连接并清理资源
  public stop() {
    console.log('SSE 连接停止');
    this.isRunning = false;
    if (this.controller) {
      this.controller.abort();
      this.controller = null;
    }
  }
}